/*
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <devmon/driver_abi.h>
#include <dlfcn.h>
#include <gtest/gtest.h>
#include <test_utilities/test_base.h>

#include "../../../drivers/bus/i2c/i2c.h"
#include "../../../drivers/chip/pca9555/pca9555.h"
#include "../../../drivers/internal/hasdef.h"
#include "../../../drivers/chip/interface/i_chip.h"
#include "../../test_utils/root_object.h"

using namespace dev;
using namespace devmon;

namespace drivers {
namespace chip {
namespace pca9555_test {

class pca9555_test_service : public mc::engine::service {
public:
    pca9555_test_service(const std::string& name) : mc::engine::service(name) {
    }
};

class Pca9555AbiTest : public mc::test::TestWithEngine {
public:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        // 动态创建服务实例，避免全局静态初始化导致的析构顺序问题
        m_test_service = mc::make_shared<pca9555_test_service>("bmc.kepler.test_pca9555");
        m_test_service->init();
        m_test_service->start();

        // 创建根对象
        m_root_object = root_object::create_root_object(m_test_service.get());

        load_driver();
    }

    static void TearDownTestSuite() {
        m_test_service->stop();
        m_root_object.reset();
        
        // 清理设备容器，避免引用已关闭的动态库
        m_devices.clear();
        m_i2c_devices.clear();

        // 不手动dlclose，避免静态对象析构时访问已卸载的动态库导致SIGSEGV
        // 让系统在程序退出时自动卸载动态库
        m_test_service.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        // 底层驱动打桩会自动管理内存，无需手动清理
    }

    void TearDown() override {
        // 底层驱动打桩会自动管理内存，无需手动清理
    }

    static void load_driver() {
        // 加载PCA9555驱动
        m_driver_handle = dlopen("./opt/bmc/drivers/libPca9555.so", RTLD_LAZY);
        if (m_driver_handle == nullptr) {
            MC_THROW(mc::system_exception, "Failed to load Pca9555 driver: ${error}",
                     ("error", dlerror()));
        }
        register_device_driver_func func = reinterpret_cast<register_device_driver_func>(
            dlsym(m_driver_handle, "register_device_driver"));
        MC_ASSERT_THROW(func, mc::bad_function_call_exception,
                        "Failed to get register_device_driver function: ${error}",
                        ("error", dlerror()));

        device_driver_t* devices       = nullptr;
        uint8_t          devices_count = 0;
        status_t         ret           = func(&devices, &devices_count);
        MC_ASSERT_THROW(ret == STATUS_OK, mc::bad_function_call_exception,
                        "Failed to get device driver manager: ${error}", ("error", ret));

        m_devices.clear();
        m_devices.reserve(devices_count);
        for (uint8_t i = 0; i < devices_count; i++) {
            auto device_driver = std::make_shared<device_driver_t>(devices[i]);
            m_devices.emplace(device_driver->device_name, device_driver);
        }

        // 加载I2C驱动
        m_i2c_driver_handle = dlopen("./opt/bmc/drivers/libI2c.so", RTLD_LAZY);
        if (m_i2c_driver_handle == nullptr) {
            MC_THROW(mc::system_exception, "Failed to load I2c driver: ${error}",
                     ("error", dlerror()));
        }
        register_device_driver_func i2c_func = reinterpret_cast<register_device_driver_func>(
            dlsym(m_i2c_driver_handle, "register_device_driver"));
        MC_ASSERT_THROW(i2c_func, mc::bad_function_call_exception,
                        "Failed to get I2c register_device_driver function: ${error}",
                        ("error", dlerror()));

        device_driver_t* i2c_devices       = nullptr;
        uint8_t          i2c_devices_count = 0;
        status_t         i2c_ret           = i2c_func(&i2c_devices, &i2c_devices_count);
        MC_ASSERT_THROW(i2c_ret == STATUS_OK, mc::bad_function_call_exception,
                        "Failed to get I2c device driver manager: ${error}", ("error", i2c_ret));

        m_i2c_devices.clear();
        m_i2c_devices.reserve(i2c_devices_count);
        for (uint8_t i = 0; i < i2c_devices_count; i++) {
            auto device_driver = std::make_shared<device_driver_t>(i2c_devices[i]);
            m_i2c_devices.emplace(device_driver->device_name, device_driver);
        }
    }

    std::shared_ptr<device_driver> create_bus_driver(const std::string& driver_name) {
        auto it = m_i2c_devices.find(driver_name);
        if (it == m_i2c_devices.end()) {
            MC_THROW(mc::invalid_op_exception, "I2c driver not found: ${name}", ("name", driver_name));
        }
        return it->second;
    }

    mc::dict create_test_connector(uint8_t system_id = 1, uint8_t position = 1, uint8_t slot = 1) {
        return {{"SystemId", system_id}, {"Position", position}, {"Slot", slot}};
    }

    mc::dict create_bus_csr_object(uint8_t bus_id, uint32_t bus_speed, uint8_t bus_mode,
                                   uint8_t bus_slave_addr, bool bus_use_smbus) {
        return {{"BusId", bus_id},
                {"BusSpeed", bus_speed},
                {"BusMode", bus_mode},
                {"BusSlaveAddr", bus_slave_addr},
                {"BusUseSmbus", bus_use_smbus}};
    }

    mc::mutable_dict create_pca9555_csr_object(uint32_t address, uint8_t offset_width, uint8_t address_width,
                                       uint32_t write_timeout, uint32_t read_timeout,
                                       uint8_t rw_block_size, uint8_t write_interval,
                                       uint8_t read_interval, uint8_t write_retry, uint8_t read_retry) {
        return {{"Address", address},
                {"OffsetWidth", offset_width},
                {"AddrWidth", address_width},
                {"WriteTmout", write_timeout},
                {"ReadTmout", read_timeout},
                {"RwBlockSize", rw_block_size},
                {"WriteInterval", write_interval},
                {"ReadInterval", read_interval},
                {"WriteRetryTimes", write_retry},
                {"ReadRetryTimes", read_retry},
                {"object_name", "test_i2c"}};
    }

protected:
    static mc::shared_ptr<pca9555_test_service>                              m_test_service;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_devices;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_i2c_devices;
    static root_object_ptr                                                   m_root_object;
    static void*                                                             m_driver_handle;
    static void*                                                             m_i2c_driver_handle;
};

mc::shared_ptr<pca9555_test_service> Pca9555AbiTest::m_test_service;
std::unordered_map<std::string, std::shared_ptr<device_driver_t>> Pca9555AbiTest::m_devices;
std::unordered_map<std::string, std::shared_ptr<device_driver_t>> Pca9555AbiTest::m_i2c_devices;
root_object_ptr                                                   Pca9555AbiTest::m_root_object;
void*                                                             Pca9555AbiTest::m_driver_handle = nullptr;
void*                                                             Pca9555AbiTest::m_i2c_driver_handle = nullptr;

// ========================= 基本功能测试 =========================

TEST_F(Pca9555AbiTest, register_device_driver_success) {
    // 验证驱动注册成功
    EXPECT_FALSE(m_devices.empty());
    EXPECT_TRUE(m_devices.find("Pca9555") != m_devices.end());
    
    auto pca9555_driver = m_devices["Pca9555"];
    EXPECT_NE(pca9555_driver, nullptr);
    EXPECT_STREQ(pca9555_driver->device_name, "Pca9555");
}

TEST_F(Pca9555AbiTest, init_pca9555_success) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x20, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建PCA9555内部对象
    std::string      pca9555_object_name = "test_pca9555_obj";
    mc::mutable_dict csr_object = create_pca9555_csr_object(0x20, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_object["object_name"]   = pca9555_object_name;
    auto pca9555_internal =
        dev::device_manager::get_instance().create_chip(pca9555_object_name, "Pca9555", csr_object);
    ASSERT_TRUE(pca9555_internal != nullptr);

    auto device_driver = m_devices["Pca9555"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(&m_test_service, pca9555_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto pca9555_obj = static_cast<dev::pca9555_object*>(device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(&m_test_service, i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化PCA9555芯片
    ret = device_driver->init(device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    pca9555_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(pca9555_obj);
    m_test_service->register_object(i2c_obj);

    // 设置连接关系
    pca9555_internal->set_left_bus(i2c_internal);
    pca9555_internal->set_host_bus(i2c_internal);

    // 验证初始化成功
    EXPECT_TRUE(pca9555_obj->m_interface_chip.m_chip != nullptr);
}

TEST_F(Pca9555AbiTest, init_pca9555_null_params) {
    auto pca9555_driver = m_devices["Pca9555"];
    
    // 测试空参数
    status_t ret = pca9555_driver->init(nullptr, nullptr, nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(Pca9555AbiTest, init_pca9555_null_device) {
    auto pca9555_driver = m_devices["Pca9555"];
    auto connector = create_test_connector();
    auto csr = create_pca9555_csr_object(0x20, 1, 1, 1000, 1000, 1, 0, 0, 3, 3);
    
    // 测试空设备句柄
    status_t ret = pca9555_driver->init(nullptr, &csr, &connector);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(Pca9555AbiTest, bit_read_write) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_bit";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x20, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建PCA9555内部对象
    std::string      pca9555_object_name = "test_pca9555_bit_obj";
    mc::mutable_dict csr_object = create_pca9555_csr_object(0x20, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_object["object_name"]   = pca9555_object_name;
    auto pca9555_internal =
        dev::device_manager::get_instance().create_chip(pca9555_object_name, "Pca9555", csr_object);
    ASSERT_TRUE(pca9555_internal != nullptr);

    auto device_driver = m_devices["Pca9555"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(&m_test_service, pca9555_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto pca9555_obj = static_cast<dev::pca9555_object*>(device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(&m_test_service, i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化PCA9555芯片
    ret = device_driver->init(device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    pca9555_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(i2c_obj);
    m_test_service->register_object(pca9555_obj);

    // 设置连接关系
    pca9555_internal->set_left_bus(i2c_internal);
    pca9555_internal->set_host_bus(i2c_internal);

    // 验证初始化成功
    EXPECT_TRUE(pca9555_obj->m_interface_chip.m_chip != nullptr);
    
    // 测试位读写操作
    // 测试位写入
    std::vector<uint8_t> write_data = {0xAA};
    pca9555_obj->m_interface_chip.BitIOWrite(0, 1, 0x0F, write_data);
    
    // 测试位读取
    std::vector<uint8_t> read_data = pca9555_obj->m_interface_chip.BitIORead(0, 1, 0x0F);
    EXPECT_FALSE(read_data.empty());
}

TEST_F(Pca9555AbiTest, bit_write_logic_validation) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_logic";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x20, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建PCA9555内部对象
    std::string      pca9555_object_name = "test_pca9555_logic_obj";
    mc::mutable_dict csr_object = create_pca9555_csr_object(0x20, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_object["object_name"]   = pca9555_object_name;
    auto pca9555_internal =
        dev::device_manager::get_instance().create_chip(pca9555_object_name, "Pca9555", csr_object);
    ASSERT_TRUE(pca9555_internal != nullptr);

    auto device_driver = m_devices["Pca9555"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(&m_test_service, pca9555_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto pca9555_obj = static_cast<dev::pca9555_object*>(device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(&m_test_service, i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化PCA9555芯片
    ret = device_driver->init(device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    pca9555_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(i2c_obj);
    m_test_service->register_object(pca9555_obj);

    // 设置连接关系
    pca9555_internal->set_left_bus(i2c_internal);
    pca9555_internal->set_host_bus(i2c_internal);

    // 验证初始化成功
    EXPECT_TRUE(pca9555_obj->m_interface_chip.m_chip != nullptr);
    
    // 获取内部的chip_pca9555对象进行直接测试
    auto chip_pca9555_ptr = static_cast<dev::chip_pca9555*>(pca9555_obj->m_interface_chip.m_chip);
    ASSERT_NE(chip_pca9555_ptr, nullptr);
    
    // 测试bit_write的参数验证逻辑
    std::vector<uint8_t> in_buffer = {0xAA};
    std::vector<uint8_t> out_buffer;
    
    // 测试空缓冲区 - 应该抛出异常
    std::vector<uint8_t> empty_buffer;
    std::string error_empty_buffer;
    EXPECT_THROW(chip_pca9555_ptr->bit_write(0, 1, 0x0F, empty_buffer, out_buffer, error_empty_buffer), std::exception);
    
    // 测试无效mask - 应该抛出异常
    std::string error_invalid_mask;
    EXPECT_THROW(chip_pca9555_ptr->bit_write(0, 1, 0, in_buffer, out_buffer, error_invalid_mask), std::exception);
    
    // 测试无效length - 应该抛出异常
    std::string error_invalid_length;
    EXPECT_THROW(chip_pca9555_ptr->bit_write(0, 2, 0x0F, in_buffer, out_buffer, error_invalid_length), std::exception);
    
    // 测试无效offset - 应该抛出异常
    std::string error_invalid_offset;
    EXPECT_THROW(chip_pca9555_ptr->bit_write(2, 1, 0x0F, in_buffer, out_buffer, error_invalid_offset), std::exception);
    
    // 测试正常情况 - 应该成功
    std::string error_normal;
    int32_t result = chip_pca9555_ptr->bit_write(0, 1, 0x0F, in_buffer, out_buffer, error_normal);
    EXPECT_EQ(result, HAS_OK);
    
    // 测试不同的offset值
    std::string error_offset_diff;
    result = chip_pca9555_ptr->bit_write(1, 1, 0x0F, in_buffer, out_buffer, error_offset_diff);
    EXPECT_EQ(result, HAS_OK);
    
    // 测试不同的mask值
    std::vector<uint32_t> masks = {0x01, 0x0F, 0xF0, 0xFF};
    for (uint32_t mask : masks) {
        std::string error_mask_diff;
        result = chip_pca9555_ptr->bit_write(0, 1, mask, in_buffer, out_buffer, error_mask_diff);
        EXPECT_EQ(result, HAS_OK);
    }
}


} // namespace pca9555_test
} // namespace chip
} // namespace drivers 